package com.briup.shopadmin.service.impl;

import com.briup.shopadmin.common.GlobalException;
import com.briup.shopadmin.service.IFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class FileServiceImpl implements IFileService {
    @Value("${nginx.path}")
    private String nginxPath;
    @Override
    public String upload(String query, MultipartFile file) {
     //后端校验数据格式
     String filename = file.getOriginalFilename();
     String[] arr = filename.split("[.]");
     String fileType = arr[arr.length-1];
     if (fileType.toLowerCase().equals("png")||fileType.toLowerCase().equals("jpg")){
         //保存图片
         String imgName = UUID.randomUUID().toString()+"."+fileType;
       File destFile =  new File(nginxPath +query+"/"+imgName);
        try {
            file.transferTo(destFile);
            return imgName;
        }catch (IOException e){
            e.printStackTrace();
            throw new GlobalException(50001,"图片写入失败");
        }

     }else {
         throw new GlobalException(50002,"上传的图片数据格式不支持");
     }
    }
}
